﻿using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace PowerShellCustomTool
{
    public class PowerShellUtil
    {
        static PowerShell _ps;
        static Runspace _rs;

        public static PowerShell ThePowerShellEngine()
        {
            if (_ps == null)
            {
                _ps = PowerShell.Create();
            }

            return _ps;
        }

        public static void ReleaseRunspace()
        {
            if (_rs != null)
            {
                _rs.Close();
            }

            _rs = null;
        }

        public static string ThePSCGProfile()
        {
            var userName = TheRunspace().SessionStateProxy.GetVariable("env:USERNAME");
            var targetPath = string.Format(@"C:\Users\{0}\Documents\WindowsPowerShell", userName);
            var pscgProfile = Path.Combine(targetPath, "PSCG.ps1");

            return pscgProfile;
        }

        public static Runspace TheRunspace()
        {
            if (_rs == null)
            {
                var iss = InitialSessionState.CreateDefault();

                AddAssemblies(iss);

                _rs = RunspaceFactory.CreateRunspace(iss);
                _rs.Open();
            }

            return _rs;
        }

        private static void AddAssemblies(InitialSessionState iss)
        {
            iss.Assemblies.Add(new SessionStateAssemblyEntry("system", "System.dll"));
            iss.Assemblies.Add(new SessionStateAssemblyEntry("System.Data", "System.Data.dll"));
        }

        public static void ReleasePowerShell()
        {
            if (_ps != null)
            {
                _ps.Dispose();
                _ps = null;
                PowerShellUtil.ReleaseRunspace();
            }
        }
    }
}
